import { createI18n } from "vue-i18n";
import zhCN from "./locales/zh-CN.js";
import enUS from "./locales/en-US.js";
import api from "@/api";

// 获取浏览器语言或本地存储的语言设置
const getDefaultLanguage = () => {
  const savedLanguage = localStorage.getItem("language");
  if (savedLanguage) {
    return savedLanguage;
  }

  const browserLanguage = navigator.language || navigator.userLanguage;
  if (browserLanguage.startsWith("zh")) {
    return "zh-CN";
  }
  return "en-US";
};

const i18n = createI18n({
  legacy: false, // 使用 Composition API 模式
  locale: getDefaultLanguage(), // 默认语言
  fallbackLocale: "zh-CN", // 回退语言
  warnHtmlMessage: false, // 禁用HTML
  messages: {
    "zh-CN": zhCN,
    "en-US": enUS,
  },
});

export default i18n;

// 切换语言的工具函数
export const switchLanguage = (locale) => {
  i18n.global.locale.value = locale;
  localStorage.setItem("language", locale);

  // 同时更新 Element Plus 语言包设置
  localStorage.setItem("elementPlusLanguage", locale);
};

// 获取当前语言
export const getCurrentLanguage = () => {
  return i18n.global.locale.value;
};

// 加载本地国际化数据
export const loadLocalData = (locale) => {
  const cachedData = localStorage.getItem(`i18n_${locale}`);
  if (cachedData) {
    i18n.global.setLocaleMessage(locale, JSON.parse(cachedData));
  } else {
    // 缓存到本地存储
    localStorage.setItem(
      `i18n_${locale}`,
      JSON.stringify(locale === "zh-CN" ? zhCN : enUS)
    );
    localStorage.setItem(`i18n_${locale}_timestamp`, Date.now().toString());
  }
  return true;
};

// 加载远程国际化数据
export const loadRemoteData = async (locale) => {
  try {
    let res = await api.internationalManagement.international.queryByLocale.get(
      locale
    );
    if (res.code == "01") {
      // 将服务器数据合并到i18n实例中
      const mergedData = deepMerge(locale === "zh-CN" ? zhCN : enUS, res.data);
      i18n.global.setLocaleMessage(locale, mergedData);
      // 缓存到本地存储
      localStorage.setItem(`i18n_${locale}`, JSON.stringify(mergedData));
      localStorage.setItem(`i18n_${locale}_timestamp`, Date.now().toString());
      return true;
    }
  } catch (error) {
    // console.error("Failed to load locale messages:", error);
    return false;
  }
};

// 深度合并函数
const deepMerge = (target, source) => {
  const result = { ...target };
  for (const key in source) {
    if (
      source[key] &&
      typeof source[key] === "object" &&
      !Array.isArray(source[key])
    ) {
      result[key] = deepMerge(result[key] || {}, source[key]);
    } else {
      result[key] = source[key];
    }
  }
  return result;
};
